package com.qyhl.webtv.commonlib.utils.view.video.detailvideo;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.media.AudioManager;
import android.os.CountDownTimer;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.AttributeSet;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.R;
import com.qyhl.webtv.commonlib.entity.live.TeleTextBean;
import com.qyhl.webtv.commonlib.utils.view.video.view.ProgressWheel;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import moe.codeest.enviews.ENDownloadView;
import moe.codeest.enviews.ENPlayView;

/**
 * Created by qyhl on 2018/4/10.
 */

public class QYVideoPlayer extends StandardGSYVideoPlayer {
    public enum PlayMode {
        //点播播放模式
        NORMAL,
        //直播播放模式
        LIVE
    }

    //亮度进度
    protected ProgressBar mBrightnessDialogProgress;

    //音量图标
    private ImageView volumeIcon;

    //多路流节目单适配器
    private CommonAdapter<TeleTextBean.MutiAdressList> commonAdapter;


    //当前播放模式，默认为普通播放类型
    private static PlayMode playMode = PlayMode.NORMAL;

    public static PlayMode getPlayMode() {
        return playMode;
    }

    private StateListener stateListener;

    private PlayerListener playerListener;

    private RecyclerView menuRecycle;

    private ImageView playError;

    //上下文 对象
    private Context mContext2;

    //多路流数据
    private List<TeleTextBean.MutiAdressList> mDataList = new ArrayList<>();

    //是否是回放
    private boolean isBack;

    //人数设置
    private TextView personNum;

    //loading动画
    private ProgressWheel progressWheel;


    //定时器任务
    protected CountDownTimer countDownTimer;

    //用于记录出错前播放的进度
    private int restartPosition = 0;

    public void setStateListener(StateListener stateListener) {
        this.stateListener = stateListener;
    }

    public void setPlayerListener(PlayerListener playerListener) {
        this.playerListener = playerListener;
    }

    public QYVideoPlayer(Context context, Boolean fullFlag) {
        super(context, fullFlag);
    }

    public QYVideoPlayer(Context context) {
        super(context);
    }

    public QYVideoPlayer(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public int getLayoutId() {
        if (mIfCurrentIsFullscreen) {
            return R.layout.qy_video_land;
        }
        return R.layout.qy_video_normal;
    }


    @Override
    protected void init(Context context) {
        super.init(context);
        personNum = (TextView) findViewById(R.id.person_num);

        menuRecycle = (RecyclerView) findViewById(R.id.menu_recycle);

        progressWheel = (ProgressWheel) findViewById(R.id.load_status);

        playError = (ImageView) findViewById(R.id.play_error);

        findViewById(getPlayStatusId()).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCurrentState == CURRENT_STATE_PAUSE) {
                    clickStartIcon();
                } else {
                    if (NetUtil.isWifi(mContext)) {
                        startPlayLogic();
                    } else {
                        showWifiDialog();
                    }
                }
            }
        });

        playError.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (restartPosition != 0) {
                    setSeekOnStart(restartPosition);
                }
                startPlayLogic();
                playError.setVisibility(GONE);
            }
        });

        setFullTopUI(context);

        if (mIfCurrentIsFullscreen) {
            setMode(playMode);
        }
    }

    /**
     * 设置全屏顶部内容
     */
    private void setFullTopUI(Context context) {
        //网络状态
        TextView netStatus = (TextView) findViewById(R.id.network_status);
        netStatus.setText(NetUtil.getNetWorkTypeName(context));

        //当前时间
        TextView currentTime = (TextView) findViewById(R.id.time);
        currentTime.setText(new SimpleDateFormat("HH:mm").format(System.currentTimeMillis()));
    }


    @Override
    protected void updateStartImage() {
        if (mStartButton instanceof ENPlayView) {
            ENPlayView enPlayView = (ENPlayView) mStartButton;
            enPlayView.setDuration(500);
            if (mCurrentState == CURRENT_STATE_PLAYING) {
                enPlayView.play();
            } else if (mCurrentState == CURRENT_STATE_ERROR) {
                enPlayView.pause();
            } else {
                enPlayView.pause();
            }
        } else if (mStartButton instanceof ImageView) {
            ImageView imageView = (ImageView) mStartButton;
            if (mCurrentState == CURRENT_STATE_PLAYING) {
                imageView.setImageResource(R.drawable.qy_video_pause);
            } else {
                imageView.setImageResource(R.drawable.qy_video_play);
            }
        }
    }

    /**
     * 设置观看人数
     *
     * @param num
     */
    public void setPersonNum(String num) {
        if (StringUtils.isNotEmpty(num)) {
            personNum.setVisibility(VISIBLE);
            personNum.setText(num);
        }
    }

    /**
     * 设置播放模式
     */
    public void setMode(PlayMode mode) {
        playMode = mode;
        if (mode == PlayMode.NORMAL) {
            findViewById(R.id.current).setVisibility(VISIBLE);
            findViewById(R.id.total).setVisibility(VISIBLE);
            findViewById(R.id.bottom_progressbar).setVisibility(VISIBLE);
            findViewById(R.id.progress).setVisibility(VISIBLE);
        } else if (mode == PlayMode.LIVE) {
            findViewById(R.id.current).setVisibility(INVISIBLE);
            findViewById(R.id.total).setVisibility(INVISIBLE);
            findViewById(R.id.bottom_progressbar).setVisibility(GONE);
            findViewById(R.id.progress).setVisibility(INVISIBLE);
        }
    }


    /**
     * 全屏收起按钮
     *
     * @return
     */
    @Override
    public int getShrinkImageRes() {
        return R.drawable.qy_video_to_normal_selector;
    }

    /**
     * 全屏展开按钮
     *
     * @return
     */
    @Override
    public int getEnlargeImageRes() {
        return R.drawable.qy_video_to_fullscreen_selector;
    }

    /**
     * 获取封面播放按钮状态
     *
     * @return
     */
    protected int getPlayStatusId() {
        return R.id.play_status;
    }

    protected int getPlayErrorId() {
        return R.id.play_error;
    }

    public void hideStatusBtn(boolean isVisible) {
        if (isVisible) {
            findViewById(getPlayStatusId()).setVisibility(VISIBLE);
            findViewById(getPlayErrorId()).setVisibility(VISIBLE);
        } else {
            findViewById(getPlayStatusId()).setVisibility(GONE);
            findViewById(getPlayErrorId()).setVisibility(GONE);
        }
    }

    public void setLiveStatusRes(int res) {
        ((ImageView) findViewById(R.id.live_tag)).setVisibility(VISIBLE);
        ((ImageView) findViewById(R.id.live_tag)).setImageResource(res);
    }


    /**
     * 获取节目单控件id
     *
     * @return
     */
    protected int getMenuId() {
        return R.id.menu_recycle;
    }

    protected int getBottomId() {
        return R.id.layout_bottom;
    }

    /**
     * 设置节目单
     *
     * @param context
     * @param dataList 节目单数据
     */
    public void setUpMenu(Context context, final List<TeleTextBean.MutiAdressList> dataList, final boolean isback) {
        mContext2 = context;
        mDataList = dataList;
        isBack = isback;
        menuRecycle.setVisibility(VISIBLE);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        menuRecycle.setLayoutManager(linearLayoutManager);
        menuRecycle.setAdapter(commonAdapter = new CommonAdapter<TeleTextBean.MutiAdressList>(context, R.layout.item_video_menu, dataList) {

            @Override
            protected void convert(ViewHolder holder, TeleTextBean.MutiAdressList bean, int position) {
                TextView titleNum = holder.getView(R.id.title_num);
                TextView titleName = holder.getView(R.id.title_name);
                LinearLayout titleBg = holder.getView(R.id.video_route_bg);

                titleNum.setText(getResources().getString(R.string.route_name) + (position + 1));

                titleName.setText(bean.getTitle());

                if (bean.getIsMain() == 1) {
                    titleBg.setBackgroundResource(R.drawable.video_menu_bg_on);
                } else {
                    titleBg.setBackgroundResource(R.drawable.video_menu_bg_off);
                }
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                release();
                for (int i = 0; i < dataList.size(); i++) {
                    if (position == i) {
                        dataList.get(i).setIsMain(1);
                    } else {
                        dataList.get(i).setIsMain(0);
                    }
                }
                commonAdapter.notifyDataSetChanged();
                if (isBack) {
                    setUp(new String(Base64.decode(dataList.get(position).getEncodePlayBackUrl(), Base64.DEFAULT)), false, getTitleTextView().getText().toString());
                } else {
                    setUp(new String(Base64.decode(dataList.get(position).getEncodeHlsUrl(), Base64.DEFAULT)), false, getTitleTextView().getText().toString());
                }

                getStartButton().performClick();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    protected void touchSurfaceDown(float x, float y) {
        super.touchSurfaceDown(x, y);
        if (playMode != PlayMode.LIVE && mCurrentState == CURRENT_STATE_PLAYING) {
            if (getCurrentPositionWhenPlaying() != 0) {
                restartPosition = getCurrentPositionWhenPlaying();
            }
        }
    }

    @Override
    protected void touchDoubleUp() {
        if (playMode != PlayMode.LIVE && mCurrentState == CURRENT_STATE_PLAYING) {
            if (getCurrentPositionWhenPlaying() != 0) {
                restartPosition = getCurrentPositionWhenPlaying();
            }
        }
        super.touchDoubleUp();
    }

    @Override
    protected void touchSurfaceMove(float deltaX, float deltaY, float y) {
        int curWidth = CommonUtil.getCurrentScreenLand((Activity) getActivityContext()) ? mScreenHeight : mScreenWidth;
        int curHeight = CommonUtil.getCurrentScreenLand((Activity) getActivityContext()) ? mScreenWidth : mScreenHeight;

        if (mChangePosition) {
            int totalTimeDuration = getDuration();
            mSeekTimePosition = (int) (mDownPosition + (deltaX * totalTimeDuration / curWidth) / mSeekRatio);
            if (mSeekTimePosition > totalTimeDuration) {
                mSeekTimePosition = totalTimeDuration;
            }
            String seekTime = CommonUtil.stringForTime(mSeekTimePosition);
            String totalTime = CommonUtil.stringForTime(totalTimeDuration);
            showProgressDialog(deltaX, seekTime, mSeekTimePosition, totalTime, totalTimeDuration);
        } else if (mChangeVolume) {
            deltaY = -deltaY;
            int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            int deltaV = (int) (max * deltaY * 3 / curHeight);
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mGestureDownVolume + deltaV, 0);
            int volumePercent = (int) (mGestureDownVolume * 100 / max + deltaY * 3 * 100 / curHeight);

            showVolumeDialog(-deltaY, volumePercent);
        } else if (!mChangePosition && mBrightness) {
            if (Math.abs(deltaY) > mThreshold) {
                float percent = (-deltaY / 2 / curHeight);
                onBrightnessSlide(percent);
                mDownY = y;
            }
        }
    }

    @Override
    protected void changeUiToPauseShow() {
        super.changeUiToPauseShow();
        if (findViewById(getPlayStatusId()) != null) {
            findViewById(getPlayStatusId()).setVisibility(VISIBLE);
        }
    }


    @Override
    protected void changeUiToCompleteShow() {
        super.changeUiToCompleteShow();
        if (!mIfCurrentIsFullscreen && stateListener != null) {
            stateListener.state(true);
        }
    }

    @Override
    protected void hideAllWidget() {
        super.hideAllWidget();
        if (!mIfCurrentIsFullscreen && stateListener != null) {
            stateListener.state(false);
        }

        if (menuRecycle.getVisibility() == View.VISIBLE) {
            menuRecycle.setVisibility(GONE);
        }
    }

    @Override
    protected void changeUiToNormal() {
        super.changeUiToNormal();
        if (findViewById(getPlayStatusId()) != null) {
            findViewById(getPlayStatusId()).setVisibility(VISIBLE);
        }
        if (progressWheel != null) {
            progressWheel.setVisibility(GONE);
        }
    }

    @Override
    protected void touchSurfaceUp() {
        if (mChangePosition) {
            int duration = getDuration();
            int progress = mSeekTimePosition * 100 / (duration == 0 ? 1 : duration);
            if (mBottomProgressBar != null) {
                mBottomProgressBar.setProgress(progress);
            }
        }

        if (getTitleTextView() != null) {
            getTitleTextView().setSelected(true);
            getTitleTextView().setFocusable(true);
            getTitleTextView().requestFocus();
        }
//        if (!mChangePosition && !mChangeVolume && !mBrightness) {
//            onClickUiToggle();
//        }

        mTouchingProgressBar = false;
        dismissProgressDialog();
        dismissVolumeDialog();
        dismissBrightnessDialog();
        if (mChangePosition && GSYVideoManager.instance().getPlayer() != null && (mCurrentState == CURRENT_STATE_PLAYING || mCurrentState == CURRENT_STATE_PAUSE) && playMode != PlayMode.LIVE) {
            try {
                GSYVideoManager.instance().getPlayer().seekTo(mSeekTimePosition);
            } catch (Exception e) {
                e.printStackTrace();
            }
            int duration = getDuration();
            int progress = mSeekTimePosition * 100 / (duration == 0 ? 1 : duration);
            if (mProgressBar != null) {
                mProgressBar.setProgress(progress);
            }
            if (mVideoAllCallBack != null && isCurrentMediaListener()) {
                Debuger.printfLog("onTouchScreenSeekPosition");
                mVideoAllCallBack.onTouchScreenSeekPosition(mOriginUrl, mTitle, this);
            }
        } else if (mBrightness) {
            if (mVideoAllCallBack != null && isCurrentMediaListener()) {
                Debuger.printfLog("onTouchScreenSeekLight");
                mVideoAllCallBack.onTouchScreenSeekLight(mOriginUrl, mTitle, this);
            }
        } else if (mChangeVolume) {
            if (mVideoAllCallBack != null && isCurrentMediaListener()) {
                Debuger.printfLog("onTouchScreenSeekVolume");
                mVideoAllCallBack.onTouchScreenSeekVolume(mOriginUrl, mTitle, this);
            }
        }

        if (!mIfCurrentIsFullscreen && stateListener != null) {
            stateListener.state(true);
        }

        if (mIfCurrentIsFullscreen) {
            setFullTopUI(mContext);
        }

        if (menuRecycle.getVisibility() == View.GONE) {
            menuRecycle.setVisibility(VISIBLE);
        }
    }

    @Override
    protected void changeUiToPreparingShow() {
        super.changeUiToPreparingShow();
        if (findViewById(getPlayStatusId()) != null) {
            findViewById(getPlayStatusId()).setVisibility(GONE);
        }

        if (progressWheel != null) {
            progressWheel.setVisibility(VISIBLE);
        }

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return super.onTouch(v, event);
    }

    @Override
    protected void changeUiToPlayingBufferingShow() {
        super.changeUiToPlayingBufferingShow();
        if (progressWheel != null) {
            progressWheel.setVisibility(VISIBLE);
        }
        startBufferDountDown();
    }

    @Override
    protected void changeUiToError() {
        Debuger.printfLog("changeUiToError");

        setViewShowState(mTopContainer, VISIBLE);
        setViewShowState(mBottomContainer, VISIBLE);
        setViewShowState(mStartButton, VISIBLE);
        setViewShowState(mLoadingProgressBar, INVISIBLE);
        setViewShowState(mThumbImageViewLayout, INVISIBLE);
        setViewShowState(mBottomProgressBar, INVISIBLE);
        setViewShowState(mLockScreen, (mIfCurrentIsFullscreen && mNeedLockFull) ? VISIBLE : GONE);

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ((ENDownloadView) mLoadingProgressBar).reset();
        }
        updateStartImage();
        if (progressWheel != null) {
            progressWheel.setVisibility(GONE);
        }

        if (playError != null) {
            playError.setVisibility(VISIBLE);
        }

        stopBufferCountDown();

    }

    @Override
    protected void changeUiToPlayingShow() {
        super.changeUiToPlayingShow();
        if (stateListener != null) {
            stateListener.closeRadio();
        }

        if (findViewById(getPlayStatusId()) != null) {
            findViewById(getPlayStatusId()).setVisibility(GONE);
        }

        if (progressWheel != null) {
            progressWheel.setVisibility(GONE);
        }

        if (playError != null) {
            playError.setVisibility(GONE);
        }

        stopBufferCountDown();
    }


    @Override
    public void startPlayLogic() {
        super.startPlayLogic();
        findViewById(getPlayStatusId()).setVisibility(GONE);
    }

    @Override
    public void onAutoCompletion() {
        super.onAutoCompletion();
        findViewById(getPlayStatusId()).setVisibility(VISIBLE);
        findViewById(getBottomId()).setVisibility(INVISIBLE);
    }

    protected int getVolumeIconId() {
        return R.id.qy_video_volume_img;
    }


    protected int getVolumeLayoutId() {
        return R.layout.video_volume_dialog_qy;
    }

    protected int getBrightnessLayoutId() {
        return R.layout.video_light_dialog_qy;
    }

    protected int getVolumeProgressId() {
        return R.id.volume_progressbar;
    }

    protected int getBrightnessTextId() {
        return R.id.app_video_brightness;
    }


    @Override
    protected void showProgressDialog(float deltaX, String seekTime, int seekTimePosition, String totalTime, int totalTimeDuration) {
        if (playMode != PlayMode.LIVE) {
            if (mProgressDialog == null) {
                View localView = LayoutInflater.from(getActivityContext()).inflate(R.layout.video_progress_dialog_qy, null);
                mDialogProgressBar = ((ProgressBar) localView.findViewById(R.id.duration_progressbar));
                if (mDialogProgressBarDrawable != null) {
                    mDialogProgressBar.setProgressDrawable(mDialogProgressBarDrawable);
                }
                mDialogSeekTime = ((TextView) localView.findViewById(R.id.tv_current));
                mDialogTotalTime = ((TextView) localView.findViewById(R.id.tv_duration));
                mDialogIcon = ((ImageView) localView.findViewById(R.id.duration_image_tip));
                mProgressDialog = new Dialog(getActivityContext(), R.style.video_style_dialog_progress);
                mProgressDialog.setContentView(localView);
                mProgressDialog.getWindow().addFlags(Window.FEATURE_ACTION_BAR);
                mProgressDialog.getWindow().addFlags(32);
                mProgressDialog.getWindow().addFlags(16);
                mProgressDialog.getWindow().setLayout(getWidth(), getHeight());
                if (mDialogProgressNormalColor != -11) {
                    mDialogTotalTime.setTextColor(mDialogProgressNormalColor);
                }
                if (mDialogProgressHighLightColor != -11) {
                    mDialogSeekTime.setTextColor(mDialogProgressHighLightColor);
                }
                WindowManager.LayoutParams localLayoutParams = mProgressDialog.getWindow().getAttributes();
                localLayoutParams.gravity = Gravity.TOP;
                localLayoutParams.width = getWidth();
                localLayoutParams.height = getHeight();
                int[] location = new int[2];
                getLocationOnScreen(location);
                localLayoutParams.x = location[0];
                localLayoutParams.y = location[1];
                mProgressDialog.getWindow().setAttributes(localLayoutParams);
            }
            if (!mProgressDialog.isShowing()) {
                mProgressDialog.show();
            }

            mDialogSeekTime.setText(seekTime);
            mDialogTotalTime.setText(" / " + totalTime);
            if (totalTimeDuration > 0) {
                mDialogProgressBar.setProgress(seekTimePosition * 100 / totalTimeDuration);
            }
            if (deltaX > 0) {
                mDialogIcon.setBackgroundResource(com.shuyu.gsyvideoplayer.R.drawable.video_forward_icon);
            } else {
                mDialogIcon.setBackgroundResource(com.shuyu.gsyvideoplayer.R.drawable.video_backward_icon);
            }
        }
    }

    @Override
    protected void dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    @Override
    protected void showVolumeDialog(float deltaY, int volumePercent) {
        if (mVolumeDialog == null) {
            View localView = LayoutInflater.from(getActivityContext()).inflate(getVolumeLayoutId(), null);
            if (localView.findViewById(getVolumeProgressId()) instanceof ProgressBar) {
                mDialogVolumeProgressBar = ((ProgressBar) localView.findViewById(getVolumeProgressId()));
                if (mVolumeProgressDrawable != null && mDialogVolumeProgressBar != null) {
                    mDialogVolumeProgressBar.setProgressDrawable(mVolumeProgressDrawable);
                }
            }
            volumeIcon = (ImageView) localView.findViewById(getVolumeIconId());
            mVolumeDialog = new Dialog(getActivityContext(), com.shuyu.gsyvideoplayer.R.style.video_style_dialog_progress);
            mVolumeDialog.setContentView(localView);
            mVolumeDialog.getWindow().addFlags(8);
            mVolumeDialog.getWindow().addFlags(32);
            mVolumeDialog.getWindow().addFlags(16);
            mVolumeDialog.getWindow().setLayout(-2, -2);
            WindowManager.LayoutParams localLayoutParams = mVolumeDialog.getWindow().getAttributes();
            localLayoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
            localLayoutParams.width = getWidth();
            localLayoutParams.height = getHeight();
            int[] location = new int[2];
            getLocationOnScreen(location);
            localLayoutParams.x = location[0];
            localLayoutParams.y = location[1];
            mVolumeDialog.getWindow().setAttributes(localLayoutParams);
        }
        if (volumeIcon != null) {
            if (volumePercent < 1) {
                volumeIcon.setImageResource(R.drawable.qy_video_volume_silence);
            } else {
                volumeIcon.setImageResource(R.drawable.qy_video_volume_normal);
            }
        }

        if (!mVolumeDialog.isShowing()) {
            mVolumeDialog.show();
        }
        if (mDialogVolumeProgressBar != null) {
            mDialogVolumeProgressBar.setProgress(volumePercent);
        }
    }

    @Override
    protected void dismissVolumeDialog() {
        if (mVolumeDialog != null) {
            mVolumeDialog.dismiss();
            mVolumeDialog = null;
        }
    }

    @Override
    protected void onBrightnessSlide(float percent) {
        mBrightnessData = ((Activity) (mContext)).getWindow().getAttributes().screenBrightness;
        if (mBrightnessData <= 0.00f) {
            mBrightnessData = 0.50f;
        } else if (mBrightnessData < 0.01f) {
            mBrightnessData = 0.01f;
        }
        WindowManager.LayoutParams lpa = ((Activity) (mContext)).getWindow().getAttributes();
        lpa.screenBrightness = mBrightnessData + percent;
        if (lpa.screenBrightness > 1.0f) {
            lpa.screenBrightness = 1.0f;
        } else if (lpa.screenBrightness < 0.01f) {
            lpa.screenBrightness = 0.01f;
        }
        showBrightnessDialog(lpa.screenBrightness);
        ((Activity) (mContext)).getWindow().setAttributes(lpa);
    }

    @Override
    protected void showBrightnessDialog(float percent) {
        if (mBrightnessDialog == null) {
            View localView = LayoutInflater.from(getActivityContext()).inflate(getBrightnessLayoutId(), null);
            if (localView.findViewById(getBrightnessTextId()) instanceof ProgressBar) {
                mBrightnessDialogProgress = (ProgressBar) localView.findViewById(getBrightnessTextId());
            }
            mBrightnessDialog = new Dialog(getActivityContext(), com.shuyu.gsyvideoplayer.R.style.video_style_dialog_progress);
            mBrightnessDialog.setContentView(localView);
            mBrightnessDialog.getWindow().addFlags(8);
            mBrightnessDialog.getWindow().addFlags(32);
            mBrightnessDialog.getWindow().addFlags(16);
            mBrightnessDialog.getWindow().setLayout(-2, -2);
            WindowManager.LayoutParams localLayoutParams = mBrightnessDialog.getWindow().getAttributes();
            localLayoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
            localLayoutParams.width = getWidth();
            localLayoutParams.height = getHeight();
            int[] location = new int[2];
            getLocationOnScreen(location);
            localLayoutParams.x = location[0];
            localLayoutParams.y = location[1];
            mBrightnessDialog.getWindow().setAttributes(localLayoutParams);
        }
        if (!mBrightnessDialog.isShowing()) {
            mBrightnessDialog.show();
        }
        if (mBrightnessDialogProgress != null) {
            mBrightnessDialogProgress.setProgress((int) (percent * 100));
        }
    }

    @Override
    protected void dismissBrightnessDialog() {
        if (mBrightnessDialog != null) {
            mBrightnessDialog.dismiss();
            mBrightnessDialog = null;
        }
    }


    @Override
    protected void cloneParams(GSYBaseVideoPlayer from, GSYBaseVideoPlayer to) {
        super.cloneParams(from, to);
        QYVideoPlayer sf = (QYVideoPlayer) from;
        QYVideoPlayer st = (QYVideoPlayer) to;

        if (st.personNum != null) {
            st.setPersonNum(sf.personNum.getText().toString());
        }

        if (st.playMode != null) {
            st.playMode = sf.playMode;
        }

        st.mContext2 = sf.mContext2;

        st.mDataList = sf.mDataList;

        st.isBack = sf.isBack;

        if (st.mDataList != null && st.mDataList.size() > 0) {
            st.setUpMenu(sf.mContext2, sf.mDataList, sf.isBack);
        }

    }


    /**
     * 启动缓冲倒计时
     */
    protected void startBufferDountDown() {
        stopBufferCountDown();
        countDownTimer = new CountDownTimer(10000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                changeUiToError();
            }
        }.start();
    }

    /**
     * 停止缓冲倒计时
     */
    protected void stopBufferCountDown() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    public void setPlayStatusVisible(boolean isVisible){
        if(isVisible){
            findViewById(getPlayStatusId()).setVisibility(VISIBLE);
        }else{
            findViewById(getPlayStatusId()).setVisibility(GONE);
        }
    }


    public interface StateListener {
        /**
         * 播放器控件是否显示
         *
         * @param isShow
         */
        void state(boolean isShow);

        void closeRadio();
    }

    public interface PlayerListener {
        void isPlay(boolean isPlay);
    }

    @Override
    protected void setStateAndUi(int state) {
        super.setStateAndUi(state);
        if (playerListener != null) {
            if (state == CURRENT_STATE_PLAYING) {
                playerListener.isPlay(true);
            } else {
                playerListener.isPlay(false);
            }
        }
    }

    @Override
    protected int getTextureParams() {
        boolean typeChanged = (GSYVideoType.getShowType() != GSYVideoType.SCREEN_TYPE_16_9);
        return (typeChanged) ? ViewGroup.LayoutParams.WRAP_CONTENT : ViewGroup.LayoutParams.WRAP_CONTENT;
    }
}
